package gui;

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

import core.objects.Book;
import core.objects.User;

public class MainForm extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;
    private static JPanelNewsFeed jpanelNewsFeed;
    private static JPanelMyProfile jpanelMyProfile;
    private static JPanelBookSearch jpanelBookSearch;
    private static JPanelUsersSearch jpanelUserSearch;    
    
    /**
     * Creates new form MainForm
     */
    public MainForm(User user) {
        MainForm.myUser = user;
        initComponents();
        initAuxComponents();
        setLocationRelativeTo(null);
        setExtendedState(MAXIMIZED_BOTH);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this
     * code. The content of this method is always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane = new javax.swing.JSplitPane();
        jPanelLeft = new javax.swing.JPanel();
        jPanelRight = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        try {
        	setIconImage(ImageIO.read(JFrameConstructDB.class.getResourceAsStream("/resources/icon.png")));
		} catch (IOException exception) {
			//do nothing, let java default icon take over
		}
        
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Loan-a-Book");
        setMinimumSize(new java.awt.Dimension(1056, 585));

        jSplitPane.setBackground(new java.awt.Color(51, 153, 255));
        jSplitPane.setDividerSize(4);
        jSplitPane.setOneTouchExpandable(true);
        jSplitPane.setOpaque(false);

        jPanelLeft.setBackground(new java.awt.Color(51, 153, 255));
        jPanelLeft.setAlignmentY(0.0F);
        jPanelLeft.setFont(new java.awt.Font("Trebuchet MS", 0, 12)); // NOI18N
        jPanelLeft.setMaximumSize(new java.awt.Dimension(180, 30000));
        jPanelLeft.setMinimumSize(new java.awt.Dimension(180, 562));
        jPanelLeft.setPreferredSize(new java.awt.Dimension(180, 562));
        jPanelLeft.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 3));
        jSplitPane.setLeftComponent(jPanelLeft);

        jPanelRight.setBackground(new java.awt.Color(51, 153, 255));
        jPanelRight.setFont(new java.awt.Font("Trebuchet MS", 0, 12)); // NOI18N
        jPanelRight.setMinimumSize(new java.awt.Dimension(700, 562));
        jPanelRight.setPreferredSize(new java.awt.Dimension(32767, 32767));

        javax.swing.GroupLayout jPanelRightLayout = new javax.swing.GroupLayout(jPanelRight);
        jPanelRight.setLayout(jPanelRightLayout);
        jPanelRightLayout.setHorizontalGroup(
            jPanelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 870, Short.MAX_VALUE)
        );
        jPanelRightLayout.setVerticalGroup(
            jPanelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 32765, Short.MAX_VALUE)
        );

        jSplitPane.setRightComponent(jPanelRight);

        jMenu1.setText("Main");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Logout");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Quit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1056, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        dispose();
        AuthenticationForm.runGUI();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        dispose();
        System.exit(0);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void runGUI(final User myUser) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
			public void run() {
                MainForm mf = new MainForm(myUser);
                mf.setVisible(true);
                mf.setTitle(mf.getTitle() + " - " + myUser.getName());
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanelLeft;
    private static javax.swing.JPanel jPanelRight;
    private static javax.swing.JSplitPane jSplitPane;
    // End of variables declaration//GEN-END:variables
    static private User myUser = null;

    static User getMyUser() {
        return myUser;
    }

    private void addSection(String text, final JPanel contentsPanel, String imgPath) {
        JLabel newLabel = new JLabel();
        newLabel.setFont(new java.awt.Font("Trebuchet MS", 0, 13)); // NOI18N
        newLabel.setForeground(new java.awt.Color(255, 255, 255));
        newLabel.setText("<html> <u>" + text + "</u></span></html>");

        JLabel imageLabel = new JLabel();
        GUIUtils.setImageAtSize(imageLabel, 25, 27, imgPath);

        JPanel sectionButtonPanel = new JPanel();
        new BoxLayout(sectionButtonPanel, BoxLayout.X_AXIS);
        sectionButtonPanel.setMaximumSize(new Dimension(150, 20));
        sectionButtonPanel.setOpaque(false);
        sectionButtonPanel.add(imageLabel);
        sectionButtonPanel.add(newLabel);
        sectionButtonPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        sectionButtonPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me) {
                if (contentsPanel instanceof JPanelMyProfile) {
                    jSplitPane.setRightComponent(jpanelMyProfile = new JPanelMyProfile(myUser));
                } else if (contentsPanel instanceof JPanelNewsFeed){
                    jSplitPane.setRightComponent(jpanelNewsFeed = new JPanelNewsFeed(MainForm.myUser.getID()));
                } else{
                    jSplitPane.setRightComponent(contentsPanel);
                } 
            }
        });
        jPanelLeft.add(sectionButtonPanel);
    }

    private void initAuxComponents() {
        addSection("News Feed", (jpanelNewsFeed = new JPanelNewsFeed(MainForm.myUser.getID())), "/resources/news.png");
        addSection("My Profile", (jpanelMyProfile = new JPanelMyProfile(null)), "/resources/profile.png");
        addSection("Find-a-Book", (jpanelBookSearch = new JPanelBookSearch()), "/resources/book.png");
        addSection("Find-a-Friend", (jpanelUserSearch = new JPanelUsersSearch()), "/resources/friends.png");
        jSplitPane.setRightComponent(jpanelNewsFeed);
    }

    static void searchForBooks(Book book) {
        jPanelRight.removeAll();
        jpanelBookSearch.search(book);
        jSplitPane.setRightComponent(jpanelBookSearch);
    }

    static void searchForUsers(Book book) {
        jPanelRight.removeAll();
        jpanelUserSearch.search(book);
        jSplitPane.setRightComponent(jpanelUserSearch);
    }

    static void searchForUsers(User user) {
        jPanelRight.removeAll();
        if (user.equals(getMyUser())) {
            jSplitPane.setRightComponent(jpanelMyProfile);
        } else {
            jpanelUserSearch.search(user);
            jSplitPane.setRightComponent(jpanelUserSearch);
        }
    }
}
